<?php
namespace app\index\controller;
use think\Db;
use think\Request; 
use app\index\model\User as UserModel;
use app\index\model\Code;

use Aliyun\DySDKLite\SignatureHelper;

class User
{
    
    public function index()
    {

        return ['message'=>'hello world'];
    }

    public function getCode(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $g = "/13[12356789]{1}\d{8}|15[1235689]\d{8}|188\d{8}/"; 
        if(preg_match($g,$phoneNumber))
        {
            $user = UserModel::get(['phonenum'=>$phoneNumber]);
            if ($user == NULL) {
                $oldCode = Code::get(['phonenum'=>$phoneNumber]);
                if($oldCode!=NULL)
                {
                    $oldCode->delete();
                }
                $newCode = rand(100000,999999);
                $code = new Code;
                $code->phonenum = $phoneNumber;
                $code->code = $newCode;
                $code->save();
                $this->sendSms($phoneNumber,$newCode);
                return ['code'=>1, 'result'=>$newCode];
            }
            else
            {
                return ['code'=>2, 'result'=>'手机号码已存在'];
            }
            
        }else
        {
            return ['code'=>0, 'result'=>'error'];
        }
    }

     public function forgetPasswd(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $g = "/13[12356789]{1}\d{8}|15[1235689]\d{8}|188\d{8}/"; 
        if(preg_match($g,$phoneNumber))
        {
            $user = UserModel::get(['phonenum'=>$phoneNumber]);
            if ($user != NULL) {
                $oldCode = Code::get(['phonenum'=>$phoneNumber]);
                if($oldCode!=NULL)
                {
                    $oldCode->delete();
                }
                $newCode = rand(100000,999999);
                $code = new Code;
                $code->phonenum = $phoneNumber;
                $code->code = $newCode;
                $code->save();
                $this->sendSms($phoneNumber,$newCode);
                return ['code'=>1, 'result'=>$newCode];
            }
            else
            {
                return ['code'=>2, 'result'=>'手机号未注册'];
            }
            
        }else
        {
            return ['code'=>0, 'result'=>'error'];
        }
    }

    public function checkCode(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $oldCode = Code::get(['phonenum'=>$phoneNumber]);
        $rightcode = $oldCode->code;
        $phoneCode = $request->post('phoneCode');
        if (strcmp($phoneCode, "$rightcode")) {
            return ['code'=>0, 'result'=>1];
        }else
        {
            return ['code'=>1, 'result'=>'ok'];
        }
    }

    public function register(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $password = $request->post('password');
        $user = new UserModel;
        $user->phonenum = $phoneNumber;
        $user->password = $password;
        $user->username = 'U'.$phoneNumber;
        if ($user->save()) {
             return ['code'=>1, 'result'=>'注册成功'];
        }else
        {
            return ['code'=>0, 'result'=>'注册失败'];
        }
    }

    public function login(Request $request)
    {
        //echo($request->get('phonenum'));
        $phoneNumber = $request->post('phonenum');
        $password = $request->post('password');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        if ($user == NULL) {
            return ['code'=>0, 'result'=>'手机号或者密码错误'];
        }
        else if (strcmp($user->password, $password)) {
            return ['code'=>0, 'result'=>'手机号或者密码错误'];
        }else
        {
             return ['code'=>1, 'result'=>(string)$user->userid];
        }
    }

    public function changeUserName(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $userName = $request->post('username');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $user->username = $userName;
       if ($user->save()) {
             return ['code'=>1, 'result'=>'修改成功'];
        }else
        {
            return ['code'=>0, 'result'=>'修改失败'];
        }
    }

    public function changePassword(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $password = $request->post('password');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $user->password = $password;
       if ($user->save()) {
             return ['code'=>1, 'result'=>'修改成功'];
        }else
        {
            return ['code'=>0, 'result'=>'修改失败'];
        }
    }

    public function changeSex(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $sex = $request->post('sex');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $user->sex = $sex;
       if ($user->save()) {
             return ['code'=>1, 'result'=>'修改成功'];
        }else
        {
            return ['code'=>0, 'result'=>'修改失败'];
        }
    }

    public function changeAge(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $age = $request->post('age');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $user->age = intval($age);
       if ($user->save()) {
             return ['code'=>1, 'result'=>'修改成功'];
        }else
        {
            return ['code'=>0, 'result'=>'修改失败'];
        }
    }

    public function changeScore(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $newScore = doubleval($request->post('score'));
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $times = $user->times;
        $score = $user->score;
        $user->times++;
        $user->score  = round(($times * $score + $newScore) / ($times + 1),2);
       if ($user->save()) {
             return ['code'=>1, 'result'=>'修改成功'];
        }else
        {
            return ['code'=>0, 'result'=>'修改失败'];
        }
    }

    public function getUserInfo(Request $request)
    {
        $phoneNumber = $request->post('phonenum');
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        if ($user != NULL) {
            return ['code'=>1, 'result'=>$user];
        }else
        {
            return ['code'=>0, 'result'=>'error'];
        }
        
    }

    public function getUserInfoById(Request $request)
    {
        $userid = $request->post('userid');
        $user = UserModel::get(['userid'=>$userid]);
        if ($user != NULL) {
            return ['code'=>1, 'result'=>$user];
        }else
        {
            return ['code'=>0, 'result'=>'error'];
        }
        
    }


    public function test()
    {
        ini_set("display_errors", "on"); // 显示错误提示，仅用于测试时排查问题
        // error_reporting(E_ALL); // 显示所有错误提示，仅用于测试时排查问题
        set_time_limit(0); // 防止脚本超时，仅用于测试使用，生产环境请按实际情况设置
        header("Content-Type: text/plain; charset=utf-8"); // 输出为utf-8的文本格式，仅用于测试

        // 验证发送短信(SendSms)接口
        $code = 123456;
        print_r($this->sendSms("15990531835",$code));
    }

    function sendSms($phonenum,$code) {

    $params = array ();

    // *** 需用户填写部分 ***

    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
    $accessKeyId = "LTAIENYFOFdsIeBX";
    $accessKeySecret = "DsehJ1BlvPNzXkGAlCub9pSlaInNbO";

    // fixme 必填: 短信接收号码
    $params["PhoneNumbers"] = $phonenum;

    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
    $params["SignName"] = "Pin车";

    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
    $params["TemplateCode"] = "SMS_134130377";

    //fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
    $params['TemplateParam'] = Array (
        "code" => "$code"
    );

    // fixme 可选: 设置发送短信流水号
    //$params['OutId'] = "12345";

    // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
    //$params['SmsUpExtendCode'] = "1234567";


    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }

    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
    $helper = new SignatureHelper();

    // 此处可能会抛出异常，注意catch
    $content = $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        ))
        // fixme 选填: 启用https
        // ,true
    );

    return $content;
}


public function upload(Request $request) {
    $file = request()->file('image');
    $phoneNumber = $request->post('phonenum');
    if (!$file) {
        return json(['success'=>'0', 'message'=>'图片接收不到']); 
    }

    $info = $file->move("/www/web/default/pic/");
    if($info){
        $savename = $info->getSaveName();
        $filename = $info->getFilename(); 
        $data = [
            'filename' => $filename,
            'savename' => $savename,
        ];
        $user = UserModel::get(['phonenum'=>$phoneNumber]);
        $url = 'http://120.77.152.49/pic/'.$savename;
        $user->userpic = $url;
        $user->save();
        return json(['success'=>'1', 'message'=>$url]);
    }

    return json(['success'=>'0', 'message'=>'上传失败']); 
}


}
